package leetCode.thread.leetCode1115;

/**
 * synchronized + 标志位+ 唤醒方式实现
 */
public class FooBar5 implements FooBar{

    private int n;

    private volatile boolean flag = true;
    private final Object foo = new Object();


    @Override
    public void foo(Runnable printFoo) throws InterruptedException {
        for(int i=0;i<n;i++){
            synchronized (foo){
                while (!flag){
                    foo.wait();
                }
                printFoo.run();
                flag = false;
                foo.notifyAll();
            }
        }
    }

    @Override
    public void bar(Runnable printBar) throws InterruptedException {
        for(int i=0;i<n;i++){
            synchronized (foo) {
                while (flag){
                    foo.wait();
                }
                printBar.run();
                flag = true;
                foo.notifyAll();
            }
        }
    }

}
